package com.xms.security.service.role;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.xms.core.config.FinalValueDefaults;
import com.xms.datacore.service.DeleterService;
import com.xms.dependency.XmsDependencyException;
import com.xms.event.core.IEventPublisher;
import com.xms.security.entity.Roles;
import com.xms.security.event.RoleDeletedEvent;
import com.xms.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * RolesDeleterService
 * </p>
 *
 * @author migo
 * @since 2021/10/8
 */
@Service
public class RolesDeleterService extends DeleterService<Roles> implements IRolesDeleterService {
    private IEventPublisher _eventPublisher;

    @Autowired
    public RolesDeleterService(IEventPublisher eventPublisher) {
        _eventPublisher = eventPublisher;
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean delete(Roles entity) throws XmsDependencyException, SQLException {
        if (entity.getRoleid().equals(FinalValueDefaults.ADMIN_ROLEID)) {
            return false;
        }
        boolean success = super.deleteById(entity.getRoleid());
        if (success) {
            //删除事件
            _eventPublisher.publish(new RoleDeletedEvent("role", entity));
        }
        return success;
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean deleteById(UUID id) throws SQLException, XmsDependencyException {
        Roles entity = super.getById(id);
        if (entity != null) {
            return this.delete(entity);
        }
        return false;
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean deleteMany(Wrapper<Roles> queryWrapper) throws SQLException, XmsDependencyException {
        List<Roles> entityList = super.list(queryWrapper);
        if (CollectionUtil.notEmpty(entityList)) {
            for (Roles entity : entityList) {
                this.delete(entity);
            }
        }
        return false;
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean deleteByIds(Collection<UUID> idList) throws SQLException, XmsDependencyException {
        if (CollectionUtil.notEmpty(idList)) {
            for (UUID id : idList) {
                this.deleteById(id);
            }
        }
        return false;
    }
}
